import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import {authApi} from "@/api/index.js";


export const useUserStore = defineStore('user', () => {
  // 状态
  const userInfo = ref(null)
  const token = ref(localStorage.getItem('token') || '')
  const isLoggedIn = ref(!!localStorage.getItem('token'))

  // 计算属性
  const isAuthenticated = computed(() => isLoggedIn.value && !!token.value)
  const userName = computed(() => userInfo.value?.username || '')
  const userId = computed(() => userInfo.value?.id || '')
  const userRole = computed(() => userInfo.value?.role || '')

  // 登录方法
  const loginUser = async (loginData) => {
    try {
      const response = await authApi.login(loginData)
      if (response.code === 200) {
        const { token: userToken, user } = response.data

        // 保存 token 到 localStorage
        localStorage.setItem('token', userToken)
        token.value = userToken

        // 保存用户信息
        userInfo.value = user
        isLoggedIn.value = true

        return { success: true, message: '登录成功' }
      } else {
        return { success: false, message: response.message || '登录失败' }
      }
    } catch (error) {
      console.error('登录错误:', error)
      return { success: false, message: '登录失败，请稍后重试' }
    }
  }

  // 注册方法
  const registerUser = async (registerData) => {
    try {
      const response = await authApi.register(registerData)
      if (response.code === 200) {
        return { success: true, message: '注册成功' }
      } else {
        return { success: false, message: response.message || '注册失败' }
      }
    } catch (error) {
      console.error('注册错误:', error)
      return { success: false, message: '注册失败，请稍后重试' }
    }
  }

  // 获取验证码
  const getCode = async (phone) => {
    try {
      const response = await authApi.sendCode(phone)
      if (response.code === 200) {
        return { success: true, message: '验证码发送成功' }
      } else {
        return { success: false, message: response.message || '验证码发送失败' }
      }
    } catch (error) {
      console.error('获取验证码错误:', error)
      return { success: false, message: '验证码发送失败，请稍后重试' }
    }
  }

  // 登出方法
  const logout = () => {
    // 清除 localStorage
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
    // 重置状态
    token.value = ''
    userInfo.value = null
    isLoggedIn.value = false
  }

  // 初始化用户信息（从 localStorage 恢复）
  const initUserInfo = () => {
    const savedUserInfo = localStorage.getItem('userInfo')
    if (savedUserInfo) {
      try {
        userInfo.value = JSON.parse(savedUserInfo)
      } catch (error) {
        console.error('解析用户信息失败:', error)
        localStorage.removeItem('userInfo')
      }
    }
  }

  // 更新用户信息
  const updateUserInfo = (newUserInfo) => {
    userInfo.value = { ...userInfo.value, ...newUserInfo }
    localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
  }

  // 检查 token 是否有效
  const checkTokenValidity = () => {
    if (!token.value) {
      return false
    }
    // 这里可以添加 token 过期检查逻辑
    // 例如：检查 token 的过期时间
    return true
  }

  // 自动登录（如果有有效的 token）
  const autoLogin = async () => {
    if (checkTokenValidity()) {
      // 这里可以调用后端 API 验证 token 并获取最新的用户信息
      // 暂时使用本地存储的信息
      initUserInfo()

      return true
    } else {
      logout()
      return false
    }
  }

  return {
    // 状态
    userInfo,
    token,
    isLoggedIn,

    // 计算属性
    isAuthenticated,
    userName,
    userId,
    userRole,

    // 方法
    loginUser,
    registerUser,
    getCode,
    logout,
    initUserInfo,
    updateUserInfo,
    checkTokenValidity,
    autoLogin
  }
})
